package com.zhf.dao;

import com.zhf.entity.OrderItem;
import com.zhf.entity.Orders;
import com.zhf.entity.Product;
import com.zhf.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: ZhaoHuanfeng
 * @Date: 2020/9/27 16:01
 */
public class OrdersDao {

    //获取 uid为 001 的用户的所有订单信息
    public List<Orders> findAllOrders(String uid) throws SQLException {
        //创建QueryRunner
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());

        //编写SQL
        String sql="select * from orders where uid=?";

        //执行SQL
        List<Orders> ordersList = queryRunner.query(sql, new BeanListHandler<Orders>(Orders.class), uid);

        return ordersList;
    }

    //获取订单编号为 order001的订单中的所有商品信息
    public List<Product> findOrderByID(String oid) throws SQLException {
        //创建QueryRunner
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());

        //编写SQL
        String sql="select pid from orderitem where oid=?";

        //执行SQL
        List<OrderItem> list = queryRunner.query(sql, new BeanListHandler<OrderItem>(OrderItem.class), oid);

        //创建集合保存商品信息
        List<Product> productList=new ArrayList<>();

        ProductDao productDao = new ProductDao();
        //遍历订单集合获取pid
        for (OrderItem orderItem:list){
            //从orderitem中获取pid
            String pid=orderItem.getPid();

            //通过pid获取订单信息
            Product productByID = productDao.findProductByID(pid);

            //将订单信息添加到集合中
            productList.add(productByID);
        }

        return productList;
    }
}
